import {
  reqAskDetailSubmit
} from '../../utils/api.js'

import {
  getReqData,
  checkName,
  checkTelephone,
  checkTextarea
} from '../../utils/util.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const eventChannel = this.getOpenerEventChannel()
    const that = this
    eventChannel.on('acceptDataFromAskPage', async function (data) {
      /**
       * count: 13
       * name: "施工咨询"
       * telephone: "12345678912"
       * url: ""
       * _id: "5e8338682db4fe2e20c0ddb8"
       */
      // console.log(data)

      wx.setNavigationBarTitle({
        title: data.name
      })

      that.setData({
        ...data
      })
    })
  },
  /**
   * 提交数据
   */
  formSubmit: async function (e) {
    const {
      name,
      telephone,
      wechat_number,
      textarea
    } = e.detail.value

    const {
      _id
    } = this.data

    const resultInfo = this.checkInfo(e)
    if (!resultInfo.flag) {
      wx.showModal({
        title: '提示',
        content: resultInfo.msg
      })

      return null;
    }

    const {
      result
    } = await reqAskDetailSubmit({
      _id,
      name,
      telephone,
      wechat_number,
      textarea
    })
    const data = getReqData(result)
    if (!data) return null

    wx.showModal({
      title: '提示',
      content: '提交成功',
      success (res) {
        if (res.confirm) {
          wx.navigateBack({
            delta: 1,
          })
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })    
  },
  /**
   * 检查输入信息是否合法
   * 这里不检查微信号
   */
  checkInfo: function (e) {
    const {
      name,
      telephone,
      textarea
    } = e.detail.value;

    const resultCheckTelephone = checkTelephone(telephone)
    if (!resultCheckTelephone.flag) return resultCheckTelephone

    const resultCheckName = checkName(name)
    if (!resultCheckName.flag) return resultCheckName

    const resultCheckTextarea = checkTextarea(textarea)
    if (!resultCheckTextarea.flag) return resultCheckTextarea

    return {
      flag: true,
      msg: ""
    };
  }
})